# encoding: utf-8

import os

import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
from core.common import get_data_dict
from config import config


def draw_data():

    data_list = get_data_dict()
    for item in data_list:
        if not item.get('is_need'):
            continue
        file_name = f'{item.get("code")}_{item.get("describe")}.xlsx'
        file_path = os.path.join(config.COOKED_PATH, item.get('cate_type'), file_name)
        if not os.path.isfile(file_path):
            continue
        df_data = pd.read_excel(file_path)
        func = globals()[config.CATE_TYPE_DISPLAY_MAP.get(item.get('cate_type'))]
        file_name = f'{item.get("code")}_{item.get("describe")}.png'
        pic_path = os.path.join(config.COOKED_PATH, item.get('cate_type'), file_name)
        func(df_data, pic_path)


def display_stock_index(df_data, pic_path):
    draw_picture(df_data, (30,), pic_path)


def display_active_bond(df_data, pic_path):
    pass

def draw_picture(df_data, mav, path):
    """
    画图
    :param df_data:
    :param mav: （30，）
    :param path:
    :return:
    """

    df_data.set_index('Date', inplace=True)
    df_data.index = pd.to_datetime(df_data.index)


    # # 计算MACD指标
    # exp12 = df['Close'].ewm(span=12, adjust=False).mean()
    # exp26 = df['Close'].ewm(span=26, adjust=False).mean()
    # macd = exp12 - exp26
    # signal = macd.ewm(span=9, adjust=False).mean()
    # hist = macd - signal
    #
    # # 创建MACD子图
    # apds = [
    #     mpf.make_addplot(macd, panel=1, color='blue', ylabel='MACD'),
    #     mpf.make_addplot(signal, panel=1, color='orange'),
    #     mpf.make_addplot(hist, type='bar', panel=1, color='gray')
    # ]

    style = mpf.make_mpf_style(
        base_mpf_style='charles',  # 继承基础样式
        rc={'font.family': 'SimHei', 'axes.unicode_minus': False}  # 设置字体为黑体
    )

    # 绘制K线图
    fig, axes = mpf.plot(df_data, type='candle', style=style,
             mav=mav,  # 30日均线
             # addplot=apds,
             volume=True,
             title='深证100 K线图(30日均线+MACD)',
             ylabel='价格',
             ylabel_lower='MACD',
             figratio=(10, 7),
             figscale=1.2,
             datetime_format='%Y-%m-%d',
             returnfig=True)

    fig.savefig(path,
                # dpi=300,  # 分辨率设置:ml-citation{ref="20,23" data="citationList"}
                # bbox_inches='tight',  # 去除白边:ml-citation{ref="9,22" data="citationList"}
                # pad_inches=0.1,  # 内边距控制
                # transparent=False
                )
    plt.close(fig)

